var Handle = require("./handle.js")

class ProxyGenerator{
  constructor(){
    this.mesh;
    this.devices;
  }
  scanGenerato(){
    var self=this;
    if (self.mesh.hasProxy()) return;
    var promise=new Promise((resolve,reject)=>{
      self.mesh.scan(function (device) {
        console.log(device);
        if (self.isMeshDevice(device)){
          self.devices.push(device);
          console.log("push devices:", self.devices)
          if (self.devices.length <= 1) self.connectProxy();
        }
      }, true);
    })
  }
  isMeshDevice(device){
    return this.mesh.netkey.endsWith(device.name) || device.name == "Mesh Ali Light";
  }
  connectProxy(i){
    if (i == null) i = 0;
    if (this.mesh.hasProxy()) return;
    Handle.findProxy(this.mesh, this.devices[i].deviceId, (res) => {
      if (res.code != 0) {
        let nexti = (i + 1) % this.devices.length;
        this.connectProxy(nexti);
        return;
      }
      this.mesh.stopScan();
      this.disconnectlisten();
    });
  }
  disconnectlisten() {
    var self=this;
    self.mesh.disconnectListen(() => {
      self.findproxy();
    });
  }
  findProxy(mesh){
    this.mesh=mesh;
    this.devices = new Array();
    this.scanGenerato();
  }
}

module.exports = ProxyGenerator;